package com.tsp_tux.demo.Service;

import com.tsp_tux.demo.Dao.*;
import com.tsp_tux.demo.Entity.*;
import com.tsp_tux.demo.Mapper.ArticleMapper;
import com.tsp_tux.demo.Mapper.UserMapper;
import com.tsp_tux.demo.Util.JieBa;
import com.tsp_tux.demo.Util.easyRespBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author 沈育洋
 */

@Service
public class ArticleServiceImp implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    TagsRepository tagsRepository;
    @Resource
    Article_TagsRepository article_tagsRepository;
    @Resource
    ArticleRepository articleRepository;
    @Resource
    EvalueRepository evalueRepository;
    @Resource
    Article_UserRepository article_userRepository;
    @Resource
    Article_User_PraiseRepository article_user_praiseRepository;

    /**
     * @param uid   String 用户ID
     * @param state int 文章状态
     * @return 通过用户ID和文章状态来获取文章
     * @author 周志伟
     */
    @Override
    public List<Article_List> getArticleByStateByUidAndState(String uid, int state) {
        return articleMapper.getArticleByStateByUidAndState(uid, state);
    }

    @Override
    public List<Article_List> getArticleByStateBySubname(String subname) {
        return articleMapper.getArticleByStateBySubname(subname);
    }

    @Override
    public List<Article_List> getArticleByStateByUsername(String username) {
        return articleMapper.getArticleByStateByUsername(username);
    }

    @Override
    public List<Article_List> getArticleByStateByUidAndSid(String uid, int sid) {
        return articleMapper.getArticleByStateByUidAndSid(uid, sid);
    }

    @Override
    public List<Article_List_2> getFiveMark(String uid) {
        return articleMapper.getFiveMark(uid);
    }

    /**
     * @param aid int 文章ID
     * @return 返回评论
     * @author 周志伟
     */
    @Override
    public List<Comments_List> getComments(int aid)
    {
        List<Comments_List> comments_Lists = articleMapper.getComments(aid);
        if(comments_Lists.isEmpty())
            return comments_Lists;
        for (Comments_List list:comments_Lists)
        {
            list.setParentId(-1);
            List<Comments_List> reply_list = articleMapper.getCommentsByAidAndParentId(aid,list.getCid());
            list.setReply(reply_list);
        }
        return comments_Lists;
    }

    /**
     * @param aid      int 文章ID
     * @param content  String 内容
     * @param parentId 父评论
     * @param uid      String 用户ID
     * @param puid     String 父评论用户ID
     * @return 是否保存成功
     * @author 周志伟
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int PreserveComment(int aid, String content, Integer parentId, String uid, String puid) {
        String puid_ = puid;
        try {
            if("-1".equals(puid))
              puid_ = null;
            if(parentId != -1)
                articleMapper.PreserveComment(aid, content, parentId, uid, puid_);
            else
                articleMapper.PreserveComment(aid, content, null,uid, puid_);

            return  0;
        } catch (Exception e){
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * @param aid int 文章ID
     * @param uid String 用户ID
     * @return 成功返回0，失败返回1，已经收藏返回2
     * @author 周志伟
     * 插入收藏关系
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int ArticleAndUserCollect(int aid, String uid) {
        try {
            if (articleMapper.getArticle_User(aid, uid) == 0) {
                articleMapper.ArticleAndUserCollect(aid, uid);
                return 0;
            } else
            {
                articleMapper.deleteArticle_User(aid, uid);
                return 2;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * 插入点赞关系
     *
     * @param aid int 文章ID
     * @param uid String 用户ID
     * @return 成功返回0，失败返回1，已经点赞返回2
     * @author 周志伟
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int ArticleAndUserPraise(int aid, String uid) {
        try {
            if (articleMapper.getArticle_User_Praise(aid, uid) == 0) {
                articleMapper.ArticleAndUserPraise(aid, uid);
                return 0;
            } else
            {
                articleMapper.deleteArticle_User_Praise(aid, uid);
                return 2;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * @param aid int 文章ID
     * @return 文章数据信息
     * @author 周志伟
     */
    @Override
    public PraiseAndCollectNum getDigital(int aid) {
        return articleMapper.getDigital(aid);
    }

    /**
     * 获取最新的三篇博客
     * @param uid 学号/工号
     * @author 刘海生
     * @return 文章列表
     */
    @Override
    public RespBean getTop3Articles(String uid) {
        List<Article> articles = articleRepository.findTop3ByUidAndStateOrderByEditTimeDesc(uid, 1);

        return easyRespBean.ok(articles);
    }

    @Override
    public List<ArticleContent_List> getArticleByAid(int aid) {
        List<ArticleContent_List> article_lists = articleMapper.getArticleByAid(aid);
        ArrayList<ArticleContent_List> result = new ArrayList<ArticleContent_List>();
        ArrayList<String> tagname = new ArrayList<String>();
        List<String> url = articleMapper.getVideoUrlByAid(aid);
        String VideoUrl;
        if(!url.isEmpty())
            VideoUrl = url.get(0);
        else
            VideoUrl = null;
        if(!article_lists.isEmpty())
        {
            for (ArticleContent_List l:article_lists) {
                tagname.add(l.getTagName());
            }
            article_lists.get(0).setTagNameList(tagname);
            article_lists.get(0).setVideo_url(VideoUrl);
            article_lists.get(0).setKeyName(article_lists.get(0).getKeyword().split("#"));
            result.add(article_lists.get(0));
        }
        return result;
    }

    public ArticleServiceImp(ArticleRepository articleRepository) {
        this.articleRepository = articleRepository;
    }

    @Override
    public RespBean getArticle(int aid) {
        Article article = articleRepository.findByAid(aid);
        if (article != null) {
            return easyRespBean.ok(article);
        }
        return easyRespBean.err();
    }

    @Override
    public RespBean searchArticle(String search) {
        List<Article> articles = articleRepository.findByTitleLike(search);
        if (articles != null) {
            return easyRespBean.ok(articles);
        }
        return easyRespBean.err();
    }
    @Override
    public List<Article_List_1>  getCommendArtical1(){
        return articleMapper.getCommendArtical();
    }

    /**
     * @param aid   int 文章ID
     * @return 删除文章并返回状态信息
     * @author 童一凡
     */
    @Override
    public int deleteArticle(int aid){return articleMapper.deleteArticle(aid);}

    /**
     * @param keyword String 关键字
     * @return 搜索文章，返回文章信息
     * @author 童一凡
     */
    @Override
    public List<String> searchArticleByKeyword(String keyword){return articleMapper.searchArticleByKeyword(keyword);}
    public Article_List_1 searchArticleByKeyword2(String aid){return articleMapper.searchArticleByKeyword2(aid);}

    /**
     * @param aid int 文章ID
     * @param uid String 用户ID
     * @return 成功返回0，失败返回1，已经收藏返回2
     * @author 周志伟
     * 查询收藏关系
     */
    @Override
    public int getArticleAndUserCollectState(int aid, String uid) {

        try {
            if (articleMapper.getArticle_User(aid, uid) == 0)
                return 0;
            else
                return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 2;
        }
    }
    /**
     * 查询点赞关系
     *
     * @param aid int 文章ID
     * @param uid String 用户ID
     * @return 成功返回0，失败返回1，已经点赞返回2
     * @author 周志伟
     */
    @Override
    public int getArticleAndUserPraiseState(int aid, String uid) {
        try {
            if (articleMapper.getArticle_User_Praise(aid, uid) == 0)
                return 0;
            else
                return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 2;
        }
    }

    @Override
    public Article_Evalue getArticleMarkByAid(int aid) {
        return new Article_Evalue(articleMapper.getArticleMarkByAid(aid),articleMapper.getEvalueNum(aid));
    }

    /**
     * @param  aid int 文章ID
     * @return 修改文章状态并返回状态信息
     * @author 谢颖
     */
    @Override
    public int rebuildArticle(int aid){return articleMapper.rebuildArticle(aid);}

    /**
     * 创建/发布/存草稿 文章
     *
     * @author 张志豪
     */
    @Override
    public RespBean creatArticle(String uid, int aid, String title, String mdContent, String summary,
                                 int sid, int state, String[] tags,int original,int atype) {
        if (state != 0 && state != 1) {
            return new RespBean(500, "文章状态错误", null);
        }
        //tags更新
        for (String str : tags) {
            if (str.equals(""))continue;
            Tags tag = tagsRepository.findByTagName(str.toUpperCase());
            if (tag == null) {
                //id自增，没用saveall
                Tags newTag = new Tags();
                newTag.setTagName(str.toUpperCase());
                tagsRepository.save(newTag);
            }
        }

        Article article = new Article();

        //判断是否为草稿（二次编辑）,article更新
        if (aid == -1) {
            System.out.println("这是一篇新文章/草稿");
        } else {
            article.setAid(aid);
        }
        article.setEditTime(new Timestamp(System.currentTimeMillis()));
        article.setTitle(title);
        article.setSummary(summary);
        article.setMdContent(mdContent);
        article.setSid(sid);
        article.setState(state);
        article.setUid(uid);
        article.setKeyword(JieBa.getKeyWords(mdContent));
        article.setOriginal(original);
        article.setAtype(atype);

        int aidd = articleRepository.save(article).getAid();

        //article_tags更新
        //先删除
        List<Article_Tags> article_tags_pre = article_tagsRepository.findAllByAid(aidd);
        for (Article_Tags at : article_tags_pre) {
            article_tagsRepository.deleteById(at.getId());
        }
        //再添加
        for (String str : tags) {
            if (str.equals(""))continue;
            Tags tag = tagsRepository.findByTagName(str.toUpperCase());
            Article_Tags article_tags = new Article_Tags();
            article_tags.setAid(aidd);
            article_tags.setTid(tag.getTid());
            article_tagsRepository.save(article_tags);
        }
        //返回状态
        if (state == 0) {
            return new RespBean(200, "保存草稿成功！", aidd);
        } else {
            return new RespBean(200, "发布文章成功！", aidd);
        }
    }

    /**
     * 给文章评分
     * @author 张志豪
     */
    @Override
    @Transactional
    public RespBean evaluateArticle(int aid, String uid, float mark) {
        if (evalueRepository.findByUidAndAid(uid, aid)!=null){
            userMapper.UpdateMark(uid,aid,mark*2);
            return easyRespBean.okWithMsg("评分成功");
        }
        //添加评分信息
        Evalue evalue=new Evalue();
        evalue.setAid(aid);
        evalue.setUid(uid);
        evalue.setMark((int)(mark*2));
        evalueRepository.save(evalue);
        return easyRespBean.okWithMsg("评分成功");
    }

    /**
     *单独获取文章分数
     * @author 张志豪
     */
    @Override
    public float getArticleScore(int aid) {
//        List<Evalue> evalueList=evalueRepository.findAllByAid(aid);
//        if (evalueList.isEmpty()){return 0;}
//        int totalMarks=evalueList.size();
//        int totalScore=0;
//        for (Evalue e:evalueList){
//            totalScore+=e.getMark();
//        }
//        return (float)totalScore/totalMarks;
        List<Float> markList=articleRepository.getArticleScoreByAid(aid);
        if (markList.size()==1&&markList.get(0)!=null)
            return markList.get(0);
        else {
            return 0;
        }

    }

    /**
     * 获取个人收藏
     * @author 张志豪
     */
    @Override
    public RespBean getMyCollect(String uid) {
        List<Article_User> article_users = article_userRepository.findAllByUid(uid);
        List<ArticleInfo> articleInfoCollects_list=new ArrayList<>();

        //收藏
        for (Article_User au : article_users) {
            Article article = articleRepository.findByAid(au.getAid());
            ArticleInfo articleInfoCollects=new ArticleInfo();
            if (article.getState()==1) {
                articleInfoCollects.setAid(article.getAid());
                articleInfoCollects.setTitle(article.getTitle());
                articleInfoCollects.setSummary(article.getSummary());
                articleInfoCollects.setEditTime(article.getEditTime());
                articleInfoCollects.setPraiseNumber(article_user_praiseRepository.countByAid(article.getAid()));

                articleInfoCollects.setMark(getArticleScore(article.getAid()));
                articleInfoCollects.setOriginal(article.getOriginal());
                articleInfoCollects_list.add(articleInfoCollects);
            }
        }
        //时间排序
        articleInfoCollects_list.sort((t1, t2) -> t2.getEditTime().compareTo(t1.getEditTime()));
        return easyRespBean.ok("获取成功", articleInfoCollects_list);
    }

    @Override
    public RespBean getHighest3(String uid) {
        return easyRespBean.ok(articleMapper.getHighest3(uid));}

    @Override
    public RespBean checkArticleScore(String uid, int aid) {
        Evalue evalue=evalueRepository.findByUidAndAid(uid, aid);
        if (evalue==null)return easyRespBean.errWithMsg("尚无评分");
        return easyRespBean.ok("获取成功",(float)evalue.getMark());
    }

    @Override
    public List<DailyStatistics> getDailyNum() {
        List<DailyStatistics> dailyStatistics = articleMapper.getDailyNum();
        if(!dailyStatistics.isEmpty())
            for (DailyStatistics l:dailyStatistics) {
                if(l.getNumber()>10)
                    l.setNumber(10);
            }
        return dailyStatistics;
    }

}
